package com.zheng.hr.rpc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.hr.dao.mapper.HrMeetingMapper;
import com.zheng.hr.dao.model.HrMeeting;
import com.zheng.hr.dao.model.HrMeetingUser;
import com.zheng.hr.rpc.api.HrDictService;
import com.zheng.hr.rpc.api.HrMeetingService;
import com.zheng.hr.rpc.api.HrMeetingUserService;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.wc.dao.model.WcNotice;
import com.zheng.wc.rpc.api.WcNoticeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2018-03-14
 */
@Service
@Transactional(rollbackFor = Exception.class)
@BaseService
public class HrMeetingServiceImpl extends BaseServiceImpl<HrMeetingMapper, HrMeeting> implements HrMeetingService {
    @Autowired
    private UpmsApiService apiService;
    @Autowired
    private HrMeetingUserService meetingUserService;
    @Autowired
    private WcNoticeService noticeService;
    @Autowired
    private HrDictService dictService;

    public boolean insertMeeting(HrMeeting meeting, String username) throws Exception {
        meeting.setCtime(new Date());
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        WcNotice notice = new WcNotice();
        if (null != upmsUser) {
            notice.setCuser(upmsUser.getUserId());
            notice.setCorganization(upmsUser.getOrganizationId());
            meeting.setCuser(upmsUser.getUserId());
            meeting.setCorganization(upmsUser.getOrganizationId());
        }
        String joinInfo = meeting.getJoinInfo();
        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(joinInfo)) {
            String[] joinInfoArray = joinInfo.split(",");
            for (String id : joinInfoArray) {
                ids.add(Integer.parseInt(id));
            }
        }
        boolean insert = insert(meeting);
        insertMeetingUsers(ids, meeting.getId());
        //添加通知
        String type = dictService.getDictValue("会议通知", "notice_type", "1");
        String state = dictService.getDictValue("已发布", "notice_state", "1");
        notice.setType(Integer.parseInt(type));
        notice.setCtime(new Date());
        notice.setStatus(OaStatus.NORMAL.getKey());
        notice.setSendTime(new Date());
        Date beginTime = meeting.getBeginTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
        String time = simpleDateFormat.format(beginTime);
        notice.setTitle("会议通知(" + time + ")");
        notice.setContent("会议名称: " + meeting.getMeetingName() + "<br/>召开地点："
                + meeting.getMeetingPlace() + "<br/>召开时间：" + time + "<br/>请准时参加！");
        noticeService.insertNotice(notice, ids, Integer.parseInt(state));
        return insert;
    }


    @Override
    public boolean updateMeeting(HrMeeting meeting) throws Exception {
        String joinInfo = meeting.getJoinInfo();
        HrMeeting oldMeeting = selectById(meeting);
        if (oldMeeting.getStatus().equals(HrMeeting.CANCEL) || oldMeeting.getStatus().equals(HrMeeting.DELETE)) {
            throw new Exception("该会议已经取消或删除，无法修改！");
        }
        WcNotice notice = new WcNotice();
        notice.setCuser(oldMeeting.getCuser());
        notice.setCorganization(oldMeeting.getCorganization());

        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(joinInfo)) {
            String[] joinInfoArray = joinInfo.split(",");
            for (String id : joinInfoArray) {
                ids.add(Integer.parseInt(id));
            }
        }
        if (StringUtils.isNotBlank(joinInfo)) {
            EntityWrapper<HrMeetingUser> entityWrapper = new EntityWrapper<>();
            entityWrapper.where("meeting_id=" + meeting.getId());
            if (meetingUserService.delete(entityWrapper)) {
                insertMeetingUsers(ids, meeting.getId());
            }
        }
        String type = dictService.getDictValue("会议通知", "notice_type", "1");
        String state = dictService.getDictValue("已发布", "notice_state", "1");
        notice.setType(Integer.parseInt(type));
        notice.setCtime(new Date());
        notice.setStatus(OaStatus.NORMAL.getKey());
        notice.setSendTime(new Date());
        Date beginTime = meeting.getBeginTime();
        if (beginTime != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
            String time = simpleDateFormat.format(beginTime);
            notice.setTitle("会议通知变更(" + time + ")");
            notice.setContent("会议名称: " + meeting.getMeetingName() + "<br/>召开地点变更为："
                    + meeting.getMeetingPlace() + "<br/>召开时间变更为：" + time + "<br/>请准时参加！");
            noticeService.insertNotice(notice, ids, Integer.parseInt(state));
        }
        return updateById(meeting);
    }

    public boolean updateMeetingsStatue(String ids, Integer status) throws Exception {
        boolean result = false;
        String[] idArray = ids.split("-");
        for (String idStr : idArray) {
            HrMeeting meeting = selectById(Integer.parseInt(idStr));
            meeting.setStatus(status);
            result = updateById(meeting);
        }
        return result;
    }

    private void insertMeetingUsers(List<Integer> ids, Integer meetingId) {
        for (Integer id : ids) {
            HrMeetingUser user = new HrMeetingUser();
            user.setUserId(id);
            user.setMeetingId(meetingId);
            meetingUserService.insert(user);
        }
    }

}
